package com.order.model.sys;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.order.shiro.ShiroUtils;
import com.order.utils.DateUtils;
import com.order.utils.JsonUtils;

/** 
* @ClassName: User 
* @Description: 后台系统用户
* @author LinBo
* @date 2014年3月22日 下午6:37:19 
*  
*/ 

@TableBind(tableName="sys_user", pkName="id")
public class SysUser extends Model<SysUser>{

	private static final long serialVersionUID = -9208256593747185835L;
	public static final SysUser dao = new SysUser();
	public static final String ID = "id";
	public static final String NAME = "name";
	public static final String PASSWORD = "password";
	public static final String GENDER = "gender";
	public static final String MAIL = "mail";
	public static final String STATUS = "status";
	public static final String LAST_UPDATED_BY = "last_updated_by";
	public static final String LAST_UPDATE_DATE = "last_update_date";
	
	/**保存*/
	public boolean mySave() {
		String password = getMD5(getStr(PASSWORD).getBytes());
		set(MAIL, getStr(MAIL));
		set(PASSWORD, password);
		set(LAST_UPDATED_BY, ShiroUtils.getUserId());
		set(LAST_UPDATE_DATE, DateUtils.nowDate());
		set(ID, null);
		return save();
	}
	
	/**更新*/
	public boolean myUpdate() {
		if (getStr(PASSWORD).length() == 32) {// 如果前台传过来是32位的字符就不修改。
			set(PASSWORD, getStr(PASSWORD));
		} else {
			set(PASSWORD, getMD5(getStr(PASSWORD).getBytes()));
		}
		set(MAIL, getStr(MAIL));
		set("last_updated_by", ShiroUtils.getUserId());
		set("last_update_date", DateUtils.getNowTime());
		return update();
	}
	
	/**
	 * 验证用户名是否被禁用
	 */
	public static boolean isUserEnabled(String userName){
		String sql = "select 1 from sys_user "
				+ " where status = '1' "
				+ " and name = ? ";
		return (dao.findFirst(sql, userName) != null);
	}
	/** 
	 * 按账户名查询对应账户 
	 */ 
	public SysUser findByLoginName(String loginName) {
		return dao.findFirst("select * from sys_user where name=?", loginName);
	}
	/**
	 * 查询登陆账户对应的
	 */
	public Collection<String> getRolesNameList(String loginName) {
		Collection<String> roles = new ArrayList<String>();
		String sql = "" 
				 + "select r.name "
				 +"  from sys_role r" 
				 +" where exists (select 1" 
				 +"  from sys_user_role ur, sys_user u" 
				 +" where r.id = ur.sys_role_id " 
				 +"   and ur.sys_user_id = u.id" 
				 +"   and u.name = '" + loginName + "')";
		
		List<SysRole> roleList = SysRole.dao.find(sql);
		if( roleList != null && !roleList.isEmpty() ){ 
			for (SysRole role : roleList) {
				roles.add(role.getStr("authcrole"));
			}
		}		
		return roles;
	}
	
	public SysUser getObj(String json) {
		try {
			return setAttrs(JsonUtils.fastjson2Map(json));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return this;
	}
	
	/* private */
	private String getMD5(byte[] src) {
		StringBuffer sb = new StringBuffer();
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			md.update(src);
			for (byte b : md.digest())
				sb.append(Integer.toString(b >>> 4 & 0xF, 16)).append(
						Integer.toString(b & 0xF, 16));
		} catch (NoSuchAlgorithmException e) {
		}
		return sb.toString();
	}
	
	// 验证是存在
	public boolean containUser(String userName) {
		return dao.findFirst("select name from sys_user where name=?",userName) == null;
	}
	
	// 更新密码
	public boolean password(String newpassword, int userid) {
		return dao.findById(userid).set("password", getMD5(newpassword.getBytes())).update();
	}
	
	// 验证旧密码
	public boolean validatorpwd(String password, int userid) {
		return dao.findFirst("select 1 from sys_user where id = ? and password = ?",userid, getMD5(password.getBytes())) != null;
	}
	
	public Map<String, Object> getUserJson(int page, int pagesize,JSONObject jsonObj) {
		String select = "select u.id, u.name, u.password, u.mail, u.status ";
		String sqlExceptSelect = "from sys_user u where 1 = 1 ";

		// 用户名
		if (StringKit.notBlank(jsonObj.getString("NAME"))) {
			String name = jsonObj.getString("NAME");
			sqlExceptSelect += "  and u.name like '%" + name + "%'";
		}
		// 状态
		if (StringKit.notBlank(jsonObj.getString("STATUS"))) {
			String status = jsonObj.getString("STATUS");
			sqlExceptSelect += "  and u.status like '%" + status + "%'";
		}
		// 邮箱
		if (StringKit.notBlank(jsonObj.getString("MAIL"))) {
			String mail = jsonObj.getString("MAIL");
			sqlExceptSelect += "  and u.mail like '%" + mail + "%'";
		}

		Page<SysUser> list = dao.paginate(page, pagesize, select,sqlExceptSelect);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", list.getList());
		map.put("Total", list.getTotalRow());
		return map;
	}

}
